package cn.yuanqiao.archive.fondsFolder.service.impl;

import cn.yuanqiao.activiti.service.ISysFileService;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.fondsFolder.domain.FondsFolder;
import cn.yuanqiao.archive.fondsFolder.domain.Model;
import cn.yuanqiao.archive.fondsFolder.mapper.FondsFolderMapper;
import cn.yuanqiao.archive.fondsFolder.service.FondsFolderService;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;

import cn.yuanqiao.system.domain.SysFile;
import com.aspose.words.Document;
import com.aspose.words.HtmlSaveOptions;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;

@Service
public class FondsFolderServiceImpl implements FondsFolderService {
    @Autowired
    private FondsFolderMapper fondsFolderMapper;
    @Autowired
    private ISysFileService remoteFileService;
    @Autowired
    private ITenantSysConfigService sysConfigService;

    private static final Logger logger = LoggerFactory.getLogger(FondsFolderServiceImpl.class);

    @Override
    public List<Model> selectModelList(Model model) {
        return fondsFolderMapper.selectModelList(model);
    }

    @Override
    public int deleteModelByIDs(String[] IDs) {
        Model model = new Model();
        /*for(int j = 0;j<IDs.length;j++){
            String id = IDs[j];
            model.setId(Long.valueOf(id));
            List<Model> models = selectModelList(model);
            Model model1 = models.get(0);
            String path = model1.getPath();
            String prefix = model1.getPrefix();
            File file = new File(prefix + path);
            if(file.exists()){
                if(file.isFile()){
                    file.delete();
                }
            }
        }*/
        int i = fondsFolderMapper.deleteModelByIDs(IDs, model.getTableName());
        return i;
    }

    @Override
    public FondsFolder selectFondsfolderByID(String ID)
    {
        FondsFolder fondsFolder = new FondsFolder();
        return fondsFolderMapper.selectFondsfolderByID(ID,fondsFolder.getTableName());
    }


    @Override
    public List<FondsFolder> selectFondsfolderList(FondsFolder bjyqFondsfolder)
    {
        Long userId = SecurityUtils.getUserId();
        bjyqFondsfolder.setUserId(userId);

        String title = bjyqFondsfolder.getTitle();
        if(StringUtils.isNotEmpty(title) && !"null".equals(title) && title.contains("_")){
            title = title.replace("_","\\_");
            bjyqFondsfolder.setTitle(title);
        }

        return fondsFolderMapper.selectFondsfolderList(bjyqFondsfolder);
    }


    @Override
    public int insertFondsfolder(FondsFolder bjyqFondsfolder)
    {
        bjyqFondsfolder.setCreateTime(DateUtils.getNowDate());
        bjyqFondsfolder.setCreateBy(SecurityUtils.getUsername());
        bjyqFondsfolder.setIsDel(0);
        bjyqFondsfolder.setUserId(SecurityUtils.getUserId());
        bjyqFondsfolder.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        bjyqFondsfolder.setIsPublish(0);
        return fondsFolderMapper.insertFondsfolder(bjyqFondsfolder);
    }

    @Override
    public int updateFondsfolder(FondsFolder bjyqFondsfolder)
    {
        bjyqFondsfolder.setUpdateTime(DateUtils.getNowDate());
        bjyqFondsfolder.setUpdateBy(SecurityUtils.getUsername());
        Integer isPublish = bjyqFondsfolder.getIsPublish();
        String content = bjyqFondsfolder.getContent();
        String content21 = bjyqFondsfolder.getContent2();
        if(StringUtils.isNotEmpty(content21) && !"null".equals(content21)){
            String content2 = content21;
            try {
                content = URLDecoder.decode(content2,"UTF-8");
                content = URLDecoder.decode(content,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //content = URLDecoder.decode(content2);
            //content = URLDecoder.decode(content);
            bjyqFondsfolder.setContent(content);
        }
        if(null!=isPublish){
            FondsFolder fondsFolder = fondsFolderMapper.selectFondsfolderByID(bjyqFondsfolder.getId().toString(), bjyqFondsfolder.getTableName());
            Date publishTime = fondsFolder.getPublishTime();
            if(1==isPublish){
                if(publishTime!=null){
                    throw new ServiceException("不可重复发布");
                }
                bjyqFondsfolder.setPublishTime(DateUtils.getNowDate());
            }
            if(0==isPublish){
                if(publishTime==null){
                    throw new ServiceException("未发布不可取消发布");
                }
                bjyqFondsfolder.setPublishTime(null);
            }
        }
        return fondsFolderMapper.updateFondsfolder(bjyqFondsfolder);
    }

    @Override
    public int deleteFondsfolderByID(String ID)
    {
        FondsFolder fondsFolder = new FondsFolder();
        FondsFolder fondsFolder1 = fondsFolderMapper.selectFondsfolderByID(ID, fondsFolder.getTableName());
        Integer isPublish = fondsFolder1.getIsPublish();
        if(1==isPublish){
            throw new ServiceException("已发布不可删除！");
        }
        return fondsFolderMapper.deleteFondsfolderByID(ID,fondsFolder.getTableName());
    }

    @Override
    public String saveModel(String id) {
        Model model1 = new Model();
        Model model = fondsFolderMapper.selectModelByID(id,model1.getTableName());
        String filePath = model.getPrefix()+model.getPath();
        String suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
        String property = System.getProperty("os.name");
        //文档中图片的临时目录
        String imagePath = "";
        if(property.startsWith("Window")){
            imagePath = "E:\\image";
        }
        if(property.startsWith("Linux")){
            imagePath = "/data/image";
        }
        String content = "";
        long start=new Date().getTime();
        logger.info("==========word文档解析开始==========");
        if("docx".equalsIgnoreCase(suffix) ||"doc".equalsIgnoreCase(suffix)){
            content = htmlInfo(filePath, imagePath);
        }else{
            throw new ServiceException("仅支持docx、doc格式");
        }
        logger.info("==========word文档解析结束==========");
        long end=new Date().getTime();
        logger.info("word文档解析耗时：：：{}毫秒",(end-start));
        return content;
    }

    public String htmlInfo(String path, String imagePath) {
        String htmlContent = "";
        imagePath = imagePath + File.separator + new Date().getTime();
        File file2 = new File(imagePath);
        if(!file2.exists()){
            file2.mkdirs();
        }
        try {
            // 下载文件到本地
            //InputStream inputStream = new URL(sourceUrl).openStream();
            InputStream inputStream = new FileInputStream(path);
            // 创建临时文件并复制输入流的内容
            Path tempFile = Files.createTempFile("temp", ".docx");
            Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
            // 关闭输入流
            inputStream.close();

            // 打开文档
            Document doc = new Document(tempFile.toString());

            // 创建HtmlSaveOptions对象并设置图像保存文件夹
            HtmlSaveOptions saveOptions = new HtmlSaveOptions();
            saveOptions.setImagesFolder(imagePath);
            saveOptions.setExportImagesAsBase64(false);

            // 将文件转换为HTML
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            doc.save(outputStream, saveOptions);

            // 获取转换后的HTML内容
            htmlContent = outputStream.toString();
            //htmlContent = htmlContent.replace("Evaluation Only. Created with Aspose.Words. Copyright 2003-2023 Aspose Pty Ltd.", "");
            //htmlContent = htmlContent.replace("Created with an evaluation copy of Aspose.Words. To discover the full versions of our APIs please visit: https://products.aspose.com/words/", "");
            //隐藏水印
            //htmlContent = htmlContent.replace("z-index:-65537", "display:none");

            //图片上传至file服务
            File file = new File(imagePath);
            if(file.isDirectory()){
                File[] files = file.listFiles();
                for(int i = 0;i<files.length;i++){
                    File file1 = files[i];
                    String name = file1.getName();
                    //String substring = name.substring(0, name.lastIndexOf("."));
                    //if(!substring.endsWith("001")){   //排除水印图片
                        logger.info("图片名称：：：{}",name);
                        String absolutePath = file1.getAbsolutePath();
                        logger.info("图片的绝对路径：：:{}",absolutePath);
                        MultipartFile mulFileByPath = getMulFileByPath(absolutePath);
                        String url = remoteFileService.uploadFile(mulFileByPath);
                        logger.info("图片上传后的url：：：{}",url);
                        htmlContent = htmlContent.replace(absolutePath,url);
                    //}
                }
                for(int j=0;j<files.length;j++){
                    File file1 = files[j];
                    if(file1.isFile()){
                        file1.delete();
                        logger.info("删除临时图片：：：{}",file1.getName());
                    }
                }
            }
            outputStream.close();
            // 删除临时文件
            Files.deleteIfExists(tempFile);
            //return htmlContent;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return htmlContent;
    }

    public MultipartFile getMulFileByPath(String picPath) {
        FileItem fileItem = createFileItem(picPath);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }

    private FileItem createFileItem(String filePath) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "textField";
        int num = filePath.lastIndexOf(".");
        String extFile = filePath.substring(num);
        FileItem item = factory.createItem(textFieldName, "text/plain", true,
                "MyFileName" + extFile);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192))
                    != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}
